# -*- coding: utf-8 -*-
#
# Copyright © 2010 Benedikt Eger
#
# This file is part of top-news-buzz.
#
# top-news-buzz is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# top-news-buzz is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with top-news-buzz.  If not, see <http://www.gnu.org/licenses/>.

import logging

from datetime import datetime, timedelta

from google.appengine.ext import webapp
from google.appengine.ext import db

from topnewsbuzz.config import Config
from topnewsbuzz.news import NewsManager
from topnewsbuzz.metrics import MetricHelper

class ScoreService(webapp.RequestHandler):

    def get(self):
        score_delay_date = datetime.now() - timedelta(minutes = Config.score_delay_minutes())
        query = db.GqlQuery('SELECT * FROM NewsArticle WHERE publish_date < :score_delay_date AND score = 0.0 AND score_date = NULL', score_delay_date = score_delay_date)
        news_list = query.fetch(Config.articles_to_score_per_pass())

        if len(news_list) == 0:
            logging.debug('Scoring %i articles.' % len(news_list))
        else:
            logging.info('Scoring %i articles.' % len(news_list))

        metrics = MetricHelper.load_metrics()

        for news in news_list:
            news.score = 0.0

            for metric in metrics:
                if metric.enabled:
                    metric_score = metric.apply(news) * metric.boost
                    logging.debug('Score of "%s" for metric "%s": %.2f.' % (news.title, metric.display_name(), metric_score))
                    news.score += metric_score               

            logging.debug('Score of "%s" before applying the score_boost: %.2f.' % (news.title, news.score))
            news.score *= news.score_boost

            if news.score > 0.0:
                NewsManager.invalidate_memcache()
                logging.info('Scoring "%s" with %.2f.' % (news.title, news.score))
            else:
                logging.debug('Article "%s" did not get a score.' % news.title)

            news.score_date = datetime.now()
            news.put()


